package conf

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"sync"
	"time"
)

var (
	once   sync.Once
	Config *configObj
)

//这里添加配置文件信息
type configObj struct {
	Server *server
	Jog    *jwt
}

type server struct {
	RunMode      string        `json:"runMode"`
	Port         int           `json:"port"`
	ReadTimeout  time.Duration `json:"readTimeout"`
	WriteTimeout time.Duration `json:"writeTimeout"`
	Level        uint          `json:"level"`
}

type jwt struct {
	JwtSecret string `json:"jwtSecret"`
}

//初始化配置文件
func Setup(ops ...Load) {
	once.Do(func() {
		vi := viper.New()
		readFunc := func(op Load, vi *viper.Viper, cf interface{}) {
			op(vi)
			if err := vi.ReadInConfig(); err != nil {
				panic(err)
			}
			if err := vi.Unmarshal(cf); err != nil {
				fmt.Println(err)
			}
		}

		for _, op := range ops {
			readFunc(op, vi, &Config)
			vi.WatchConfig()
		}

		vi.OnConfigChange(func(in fsnotify.Event) {
			c := new(configObj)
			log.Println("读取配置文件中：", in)
			defer func() {
				re := recover()
				if re != nil {
					log.Println("监听配置文件修改出错：", re)
				}
			}()
			for _, op := range ops {
				readFunc(op, vi, c)
			}
			Config = c
		})
	})

}

//需要读取配置到 Viper 对象
type Load func(*viper.Viper)
